package xcore

import (
	"context"
	"math/rand"
)

const (
	CODE_TYPE_DIGIT = 1
	CODE_TYPE_ALPHA = 2
	letterAlpha     = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
	letterDigit     = "0123456789"
)

func RandString(n int, ctype int) string {

	randset := letterAlpha
	if ctype == CODE_TYPE_DIGIT {
		randset = letterDigit

	} else if ctype == CODE_TYPE_ALPHA {
		randset = letterAlpha
	}

	b := make([]byte, n)
	for i := range b {
		b[i] = randset[rand.Intn(len(randset))]
	}
	return string(b)
}

type RandomElement struct {
	Key    string `json:"key"`
	Weight int    `json:"weight"`
}

func WeightRandom(ctx context.Context, elems []*RandomElement) *RandomElement {
	var sum int
	var validElems = make([]*RandomElement, 0)
	for _, elem := range elems {
		if elem.Weight <= 0 || len(elem.Key) == 0 {
			continue
		}
		validElems = append(validElems, elem)
		sum += elem.Weight
	}
	if len(validElems) == 0 {
		return nil
	}
	r := rand.Intn(sum)
	var currentIndex int
	for _, elem := range validElems {
		currentIndex += elem.Weight
		if currentIndex >= r {
			return elem
		}
	}
	return nil
}
